Skip to content

[do not merge] feat: Span streaming & new span API#5551

Draft
sentrivana wants to merge 154 commits intomasterfrom
feat/span-first
Draft

[do not merge] feat: Span streaming & new span API#5551
sentrivana wants to merge 154 commits intomasterfrom
feat/span-first

Conversation

@sentrivana
Copy link
Contributor

Introduce a new start_span() API with a simpler and more intuitive signature to eventually replace the original start_span() and start_transaction() APIs.

Additionally, introduce a new streaming mode (sentry_sdk.init(_experiments={"trace_lifecycle": "stream"})) that will send spans as they finish, rather than by transaction.

import sentry_sdk

sentry_sdk.init(
    _experiments={"trace_lifecycle": "stream"},
)

with sentry_sdk.traces.start_span(name="my_span"):
    ...

The new API MUST be used with the new streaming mode, and the old API MUST be used in the legacy non-streaming (static) mode.

Migration guide: getsentry/sentry-docs#16072

Notes

  • The diff is huge mostly because I've optimized for easy removal of legacy code in the next major, deliberately duplicating a lot. I'll of course split it up to reviewable PRs once ready.
    • Chose to go with a new file and a new span class so that we can just remove the old Span and drop the new StreamedSpan in tracing.py as a replacement.
  • The batcher for spans is a bit different from the logs and metrics batchers because it needs to batch by trace_id (we can't send spans from different traces in the same envelope).

Release Plan

  • There will be prereleases for internal testing.
  • We'll release the new API in a minor version as opt-in.
  • In the next major, we'll drop the legacy API.

Project

https://linear.app/getsentry/project/span-first-sdk-python-727da28dd037/overview

@sentrivana sentrivana changed the title Feat/span first [do not merge] feat: Span streaming & new span API Feb 26, 2026
@github-actions
Copy link
Contributor

github-actions bot commented Feb 26, 2026

Semver Impact of This PR

None (no version bump detected)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


This PR will not appear in the changelog.


🤖 This preview updates automatically when you update the PR.

@github-actions
Copy link
Contributor

github-actions bot commented Feb 26, 2026

Codecov Results 📊

13 passed | Total: 13 | Pass Rate: 100% | Execution Time: 12.27s

All tests are passing successfully.

❌ Patch coverage is 22.53%. Project has 14450 uncovered lines.

Files with missing lines (43)
File Patch % Lines
tracing_utils.py 39.24% ⚠️ 429 Missing and 28 partials
__init__.py 5.28% ⚠️ 377 Missing
starlette.py 5.26% ⚠️ 360 Missing
scope.py 67.05% ⚠️ 289 Missing and 69 partials
client.py 55.38% ⚠️ 224 Missing and 59 partials
anthropic.py 9.03% ⚠️ 252 Missing
traces.py 27.14% ⚠️ 247 Missing
strawberry.py 7.76% ⚠️ 226 Missing
utils.py 16.35% ⚠️ 220 Missing
huggingface_hub.py 9.42% ⚠️ 173 Missing
rust_tracing.py 0.00% ⚠️ 163 Missing
asgi.py 19.38% ⚠️ 129 Missing
spotlight.py 28.47% ⚠️ 103 Missing and 8 partials
asgi.py 0.00% ⚠️ 109 Missing
envelope.py 54.04% ⚠️ 91 Missing and 17 partials
caching.py 0.00% ⚠️ 106 Missing
asyncpg.py 11.86% ⚠️ 104 Missing
stdlib.py 53.51% ⚠️ 86 Missing and 15 partials
templates.py 0.00% ⚠️ 100 Missing
utils.py 13.79% ⚠️ 100 Missing
httpx.py 12.15% ⚠️ 94 Missing
middleware.py 0.00% ⚠️ 90 Missing
_wsgi_common.py 30.71% ⚠️ 88 Missing and 1 partials
graphene.py 13.48% ⚠️ 77 Missing
sqlalchemy.py 10.71% ⚠️ 75 Missing
monitoring.py 17.44% ⚠️ 71 Missing
transactions.py 0.00% ⚠️ 67 Missing
__init__.py 86.43% ⚠️ 38 Missing and 23 partials
api.py 63.52% ⚠️ 58 Missing
views.py 0.00% ⚠️ 50 Missing
_span_batcher.py 30.99% ⚠️ 49 Missing
signals_handlers.py 0.00% ⚠️ 44 Missing
threading.py 63.16% ⚠️ 35 Missing and 5 partials
utils.py 68.54% ⚠️ 28 Missing and 11 partials
caches.py 47.62% ⚠️ 33 Missing and 2 partials
_async_common.py 75.36% ⚠️ 17 Missing and 7 partials
_compat.py 41.03% ⚠️ 23 Missing
_sync_common.py 76.06% ⚠️ 17 Missing and 6 partials
redis_cluster.py 52.94% ⚠️ 16 Missing
feature_flags.py 57.58% ⚠️ 14 Missing
_types.py 60.00% ⚠️ 12 Missing
queries.py 88.57% ⚠️ 4 Missing and 3 partials
consts.py 99.43% ⚠️ 2 Missing

Generated by Codecov Action

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Race condition causes span loss when buffer is at flush threshold (sentry_sdk/_span_batcher.py:19)

When MAX_BEFORE_FLUSH (1000) equals MAX_BEFORE_DROP (1000), a race condition exists where spans are unnecessarily dropped. After the 1000th span triggers a flush and releases the lock, subsequent add() calls can acquire the lock before the flush thread clears the buffer, seeing size >= MAX_BEFORE_DROP and dropping spans. This results in data loss during high-throughput scenarios.

Async Redis spans are not closed when exceptions occur (sentry_sdk/integrations/redis/_async_common.py:135)

In _sentry_execute_command, spans are created via __enter__() but __exit__() is called outside of a try/finally block. If old_execute_command raises an exception, the db_span and cache_span will never be closed, causing span leaks. The sync version in _sync_common.py correctly wraps this in a try/finally block (lines 141-151).

AttributeError when legacy Span is on scope during streaming mode (sentry_sdk/scope.py:1249)

At line 1249, parent_span is assigned from self.span or self.get_current_scope().span, which can be a legacy Span (from sentry_sdk.tracing). However, at line 1284, the code accesses parent_span.segment, an attribute that only exists on StreamedSpan, not on the legacy Span class. If streaming mode is enabled but a legacy Span ends up on the scope (e.g., from a third-party integration or mixed code), this will cause an AttributeError: 'Span' object has no attribute 'segment'.

Span silently dropped when end() called without start() (sentry_sdk/traces.py:341)

When span.end() is called without first calling span.start() or using the context manager, the _context_manager_state attribute is not initialized. The code at line 342 attempts to unpack this attribute, and the resulting AttributeError is swallowed by capture_internal_exceptions(). The span is silently dropped without any warning to the user, and the scope's span reference is not restored.

Identified by Warden find-bugs

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing try/finally causes span leak when Redis command raises exception (sentry_sdk/integrations/redis/_async_common.py:137)

In _sentry_execute_command, the async version does not wrap the await old_execute_command() call in a try/finally block, unlike the sync version in _sync_common.py. If the Redis command raises an exception, db_span.__exit__() and cache_span.__exit__() will never be called, causing the spans to remain unclosed. This could lead to resource leaks and corrupted tracing state.

Scope corruption when real_putrequest raises exception in streaming mode (sentry_sdk/integrations/stdlib.py:127)

In the span streaming code path (lines 109-127), span.start() is called which sets the span as active on the scope and saves the old span in _context_manager_state. If real_putrequest() at line 148 raises an exception, span.end() in getresponse is never called, leaving the scope's span attribute pointing to an orphaned span and never restoring the previous span. This corrupts the scope state for subsequent operations in the same request/thread.

Dict rules with unrecognized keys in ignore_spans config silently ignore ALL spans (sentry_sdk/tracing_utils.py:1498)

When ignore_spans contains a dict with only unrecognized keys (e.g., a typo like {"nme": "/health"} instead of {"name": "/health"}), both name_matches and attributes_match default to True, causing the rule to match ALL spans. This could silently drop all trace data due to a simple configuration mistake.

Identified by Warden find-bugs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants